import { _decorator, Vec2 } from 'cc';

export class GridNode {
    // 节点在网格中的坐标
    private _x: number = 0;
    private _y: number = 0;
    // 节点是否可通行
    private _walkable: boolean = true;
    // 寻路消耗
    private _g: number = 0;  // 从起点到该点的实际代价
    private _h: number = 0;  // 从该点到终点的预估代价
    private _f: number = 0;  // f = g + h
    // 父节点，用于回溯路径
    private _parent: GridNode = null;

    constructor(x: number, y: number, walkable: boolean = true) {
        this._x = x;
        this._y = y;
        this._walkable = walkable;
    }

    public get x(): number { return this._x; }
    public get y(): number { return this._y; }
    public get walkable(): boolean { return this._walkable; }
    public set walkable(value: boolean) { this._walkable = value; }
    
    public get g(): number { return this._g; }
    public set g(value: number) { 
        this._g = value;
        this._f = this._g + this._h;
    }
    
    public get h(): number { return this._h; }
    public set h(value: number) { 
        this._h = value;
        this._f = this._g + this._h;
    }
    
    public get f(): number { return this._f; }
    public get parent(): GridNode { return this._parent; }
    public set parent(value: GridNode) { this._parent = value; }

    // 重置节点数据，用于复用节点
    public reset(): void {
        this._g = 0;
        this._h = 0;
        this._f = 0;
        this._parent = null;
    }

    // 计算到另一个节点的曼哈顿距离
    public manhattanDistance(target: GridNode): number {
        return Math.abs(this._x - target.x) + Math.abs(this._y - target.y);
    }

    // 计算到另一个节点的欧几里得距离
    public euclideanDistance(target: GridNode): number {
        const dx = this._x - target.x;
        const dy = this._y - target.y;
        return Math.sqrt(dx * dx + dy * dy);
    }

    // 获取世界坐标（假设每个格子大小为1单位）
    public getWorldPosition(gridSize: number = 1): Vec2 {
        return new Vec2(this._x * gridSize, this._y * gridSize);
    }
}